package com.iwe3.protal.handler;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect //备注：去掉 依赖中的 scope 标签
@Component
public class SystemRuntimeLogAspect {

    @Pointcut("execution(* com.iwe3.protal.controller.*.*(..))")
    public void pointcut(){}

    @Around("pointcut()")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        Object target = pjp.getTarget();
        String clsName = target.getClass().getName();
        //转换方法签名
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        String methName = ms.getMethod().getName();
        //参数
        Object[] args = pjp.getArgs();
        String params = JSONUtil.toJsonStr(args);

        log.info("{}-{}-接收：{}",clsName,methName,params);
        //调用：真正的业务方法
        Object res = pjp.proceed(args);
        log.info("{}-{}-返回：{}",clsName,methName,JSONUtil.toJsonStr(res));
        return res;
    }

    @AfterThrowing(value = "pointcut()",throwing = "e")
    public void recordErrorLog(JoinPoint jp, Exception e){
        log.error("异常：{}",e);
    }
}
